import React, { useState } from 'react'
import { AutoComplete, message } from 'antd'
import _ from 'loadsh'
import PropTypes from 'prop-types'
import { awaitWrap } from '@js/tool'
import { getInfoListByName, getDataByFullName } from '../ajax/partyAjax'
import style from './AutoNameInput.module.less'
const { Option } = AutoComplete

// 改变名称
async function changeName (name, type, setLoading, setInfoList) {
  setInfoList([])
  if (name) {
    setLoading(true)
    const [e, data] = await awaitWrap(getInfoListByName(name, type, setLoading, setInfoList))
    setLoading(false)
    if (e) {
      return message.warning(e.message, 2)
    }
    setInfoList(data)
  }
}

const searchHandle = _.debounce(changeName, 600) // 缓动

// 格式化企业数据
function formatData (data = {}) {
  if (data.tag) {
    try {
      data.tag = JSON.parse(data.tag)
      data.subject_type_tag = data.tag.subject_type_tag
      data.subject_type = (this.state.typeList[data.subject_type_tag] || {}).value
    } catch (e) {
      data.tag = {}
    }
  }
  if (!['本地', '外省', '港', '澳', '台', '外国'].includes(data.area)) {
    delete data.area
  }
  return data
}

// 选择当事人信息
async function selectPersonInfo (formRef, data, index, type, infoList, setInfoList) {
  const c = formRef.current
  if (!data.address) {
    const hide = message.loading('加载中', 120)
    const [e, d] = await awaitWrap(getDataByFullName(data.name, type))
    const list = [...infoList]
    if (d) {
      list.splice(index, 1, d)
    }
    setInfoList(list)
    hide()
    if (e) {
      console.error(e)
      return message.warning(e.message, 2)
    }
    if (d) {
      data = d
    }
  }
  data = formatData(data)
  const keys = Object.keys(data)
  const map = {}
  keys.forEach(key => {
    map[key] = data[key] || ''
  })
  delete map.id
  c.setFieldsValue(map)
}

function Main ({ name, formRef, type, value, onChange }) {
  const [loading, setLoading] = useState(false)
  const [infoList, setInfoList] = useState([])
  const notice = <div>{loading ? '检索中' : '无匹配数据'}</div>
  return (
    <AutoComplete value={value} placeholder={`请输入${name}`} onSearch={v => searchHandle(v, type, setLoading, setInfoList)} onChange={onChange} notFoundContent={notice}>
      {infoList.map((li, i) => {
        return (
          <Option key={i} value={li.name}>
            <div className={style.option} onClick={() => selectPersonInfo(formRef, li, i, type, infoList, setInfoList)}>{`${li.name}（证件号：${li.license || '无'}）`}</div>
          </Option>
        )
      })}
    </AutoComplete>
  )
}

Main.propTypes = {
  formRef: PropTypes.object,
  type: PropTypes.string,
  value: PropTypes.string,
  onChange: PropTypes.func
}

Main.defaultProps = {
  formRef: null,
  type: '',
  value: '',
  onChange: () => {}
}

export default Main
